<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="批次名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入批次名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="批次编号" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入批次编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="开始时间" prop="timeLimitStart">
        <el-date-picker clearable v-model="queryParams.timeLimitStart" type="date" value-format="yyyy-MM-dd" placeholder="请选择订购开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="timeLimitEnd">
        <el-date-picker clearable v-model="queryParams.timeLimitEnd" type="date" value-format="yyyy-MM-dd" placeholder="请选择订购结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:batch:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['system:batch:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:batch:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['system:batch:export']">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="batchList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="批次名称" align="center" prop="name" />
      <!-- <el-table-column label="批次编号" align="center" prop="number" /> -->
      <el-table-column label="订购开始时间" align="center" prop="timeLimitStart" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.timeLimitStart)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="订购结束时间" align="center" prop="timeLimitEnd" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.timeLimitEnd)}}</span>
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:batch:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:batch:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-download" @click="handleExport(scope.row)" v-hasPermi="['system:order:export']">导出</el-button>
          <el-button size="mini" type="text" icon="el-icon-view" @click="handlePreview(scope.row)">预览</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改商品批次对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="批次名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入批次名称" />
        </el-form-item>
        <!-- <el-form-item label="批次编号" prop="number">
          <el-input v-model="form.number" placeholder="请输入批次编号" />
        </el-form-item> -->
        <el-form-item label="开始时间" prop="timeLimitStart">
          <el-date-picker clearable v-model="form.timeLimitStart" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择订购开始时间" style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="timeLimitEnd">
          <el-date-picker clearable v-model="form.timeLimitEnd" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择订购结束时间" style="width: 100%;">
          </el-date-picker>
        </el-form-item>

        <el-card shadow="always" :body-style="{ padding: '20px' }" v-if="isProductCardShow">
          <div slot="header">
            <span>商品</span>
            <el-button style="float: right; padding: 3px 0;color: yellowgreen;" type="text" @click="exportBatchProduct">导入</el-button>
            <el-button style="float: right;margin-right: 10px; padding: 3px 0" type="text" @click="addBatchProduct">添加</el-button>
          </div>
          <el-row :gutter="20" v-for="(item,index) in batchProductList" :key="index+new Date()" >
            <el-col :span="4" :offset="0">
              <div>序号</div>
              <div><el-input v-model="item.sort"  size="normal"></el-input>
              </div>
            </el-col>
            <el-col :span="4" :offset="0">
              <div>类别</div>
              <div><el-input v-model="item.productCategoryName"  size="normal"></el-input>
              </div>
            </el-col>
            <el-col :span="6" :offset="0">
              <div>商品</div>
              <div><el-input v-model="item.productName"  size="normal"></el-input>
              </div>
            </el-col>
            <el-col :span="4" :offset="0">
              <div>原价</div>
              <div>
                <el-input-number v-model="item.originalPrice" size="normal" @input='inputChange' :min="0" :step="0.01" :controls="true" controls-position="right" style="width: 100%;">
                </el-input-number>
              </div>
            </el-col>
            <el-col :span="6" :offset="0">
              <div>现价</div>
              <div style="display: inline-flex">
                <el-input-number v-model="item.price" size="normal" @input='inputChange' :min="0" :step="0.01" :controls="true" controls-position="right" style="width: 100%;">
                </el-input-number>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteProduct(index)">删除</el-button>
              </div>

            </el-col>
          </el-row>

          <!-- <el-row :gutter="20" v-for="(item,index) in batchProductList" :key="index+new Date()" v-if="isCardShow">
            <el-col :span="11" :offset="0">
              <div style="display: grid;grid-template-columns: 40px calc(100% - 40px);lign-items: center;">
                <div>名称</div>
                <div>
                  <treeselect v-model="item.productId" :options="productTreeList" :normalizer="normalizer" placeholder="选择商品" :disable-branch-nodes="true" :show-count="true" :appendToBody="true" z-index="9999">
                  </treeselect>
                </div>

              </div>

            </el-col>
            <el-col :span="11" :offset="0">
              <div style="display: grid;grid-template-columns: 40px calc(100% - 40px);align-items: center;">
                <div>数量</div>
                <el-input-number v-model="item.productNumber" size="normal" @input='inputChange' :min="0" :step="1" :controls="true" controls-position="right" style="width: 100%;">
                </el-input-number>
              </div>

            </el-col>
            <el-col :span="2" :offset="0" style="height: 100%;align-items: center">
              <div style="line-height: 40px;">
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteProduct(index)">删除</el-button>
              </div>

            </el-col>
          </el-row> -->

          <!-- card body -->
        </el-card>
        <!-- <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item> -->


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
              <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                  <div class="el-upload__tip" slot="tip">
                  </div>
                  <span>仅允许导入xls、xlsx格式文件。</span>
                  <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link> -->
                </div>
              </el-upload>
              <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
              </div>
            </el-dialog>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="预览"
      :visible.sync="isPreviewShow"
      width="70%"
      @close="isPreviewShow = false">
      <!-- <el-tabs type="border-card">
        <el-tab-pane label="总表"></el-tab-pane>
    <el-tab-pane v-for="(value,key) in tabList" :key="key" :label="key">
      <el-table show-summary :data="value">
        <el-table-column label="姓名" align="center" prop="nickName" />
        <el-table-column label="产品" align="center" prop="productName" />
        <el-table-column label="数量" align="center" prop="productNumber" />
        <el-table-column label="总价" align="center" prop="total" />
      </el-table>
    </el-tab-pane>
  </el-tabs> -->
  <el-tabs type="border-card">
    <el-tab-pane v-for="(value,key) in tabList" :key="key" :label="key">
      <div class="tab-row">
        <div v-for="value1 in value" style="display: flex;flex-wrap: wrap;text-align: center;white-space: nowrap;">
          <div v-for="(value2,index2) in value1" style="flex: 1;border: 1px solid;overflow: hidden; text-overflow: ellipsis;" :style="index2==0?'flex:1 1 10%;':''">
            {{ value2 }}
          </div>
        </div>

      </div>    
      
    </el-tab-pane>
  </el-tabs> 
  
    </el-dialog>
    
  </div>
</template>

<script>
import { updateBatchProduct,getBatchProductById,listBatch, getBatch, delBatch, addBatch, updateBatch, addBatchProduct, getBatchListAll } from "@/api/system/batch";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listProductTree } from '@/api/system/product';
import * as XLSX from 'xlsx/xlsx.mjs';
import { getToken } from "@/utils/auth";
import {previewOrder} from "@/api/system/order"
export default {
  name: "Batch",
  components: { Treeselect },
  data() {
    return {
      isPreviewShow:false,
      tabList:'',
      isCardShow: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品批次表格数据
      batchList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/batch/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        number: null,
        timeLimitStart: null,
        timeLimitEnd: null,
      },
      productTreeList: '',
      batchProductList: [],
      // 表单参数
      form: {},
      isProductCardShow:true,
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        // number: [
        //   { required: true, message: "编号不能为空", trigger: "blur" }
        // ],
        // timeLimitStart: [
        //   { type: 'date', required: true, message: '请选择开始时间', trigger: 'change' }
        // ],
        // timeLimitEnd: [
        //   { type: 'date', required: true, message: '请选择结束时间', trigger: 'change' }
        // ],
      }
    };
  },
  created() {
    this.getList();
    this.loadTree();
  },
  methods: {
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/batch/importTemplate', {
      }, `product_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },

    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.isProductCardShow = false;
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.batchProductList.push(...response.data);
      this.isProductCardShow = true;
      // debugger
      // this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
      this.isProductCardShow = true;
      // this.upload.open = false;
    },
    handleChange() {

    },
    exportBatchProduct() {

      this.upload.title = "商品导入";
      this.upload.open = true;
    },
    inputChange() {
      this.isProductCardShow = false;
      this.isProductCardShow = true;
      // this.$forceUpdate();
    },
    treeSelect() {
      // this.$forceUpdate();
    },
    addBatchProduct() {
      let entity = {
        productName: '',
        price: 0,
        originalPrice: 0,
        productId: null,
        batchId: null,
        categoryId: null,
        outProductId: null,
        pic: null,
        albumPics: null,
        publishStatus: 0,
        sort: null,
        price: null,
        unit: null,
        weight: null,
        detailHtml: null,
        detailMobileHtml: null,
        brandName: null,
        productCategoryName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        productAttr: null
      };
      // let entity = {
      //   pmsBatchProductId: null,
      //   batchId: null,
      //   productId: '',
      //   productNumber: 0,
      // };
      this.isProductCardShow = false;
      this.batchProductList.push(entity);
      this.isProductCardShow = true;
      console.log(this.batchProductList)

    },



    handleDeleteProduct(index) {
      this.batchProductList.splice(index, 1);
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    loadTree() {
      listProductTree('').then(res => {
        this.productTreeList = res.data;
        // debugger
      })
    },
    /** 查询商品批次列表 */
    getList() {
      this.loading = true;
      listBatch(this.queryParams).then(response => {
        this.batchList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

      // getBatchListAll('').then(res=>{
      //   debugger
      // })
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        batchId: null,
        name: null,
        number: null,
        timeLimitStart: null,
        timeLimitEnd: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.batchProductList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.batchId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品批次";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const batchId = row.batchId || this.ids
      getBatchProductById(batchId).then(response => {
        this.form = response.data.pmsBatch;
        this.batchProductList = response.data.pmsProducts;
        this.open = true;
        this.title = "修改商品批次";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.batchId != null) {
            // updateBatch(this.form).then(response => {
            //   this.$modal.msgSuccess("修改成功");
            //   this.open = false;
            //   this.getList();
            // });
            let p = {
              pmsBatch: this.form,
              pmsProducts: this.batchProductList
            };
            updateBatchProduct(p).then(response=>{
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            })
          } else {
            let f = {
              pmsBatch: this.form,
              pmsProducts: this.batchProductList
            };
            addBatchProduct(f).then(response => {
              
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });

            // addBatch(f).then(response => {
            //   this.$modal.msgSuccess("新增成功");
            //   this.open = false;
            //   this.getList();
            // });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const batchIds = row.batchId || this.ids;
      this.$modal.confirm('是否确认删除商品批次编号为"' + batchIds + '"的数据项？').then(function () {
        return delBatch(batchIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport(e) {
     
      let entity = {batchId:e.batchId};
      this.download('system/order/exportOrderExcel', {
        ...entity
      }, `${e.name}.xlsx`)
      // this.download('system/batch/export', {
      //   ...this.queryParams
      // }, `batch_${new Date().getTime()}.xlsx`)
    },

    handlePreview(e){
      this.tabList = '';
      let t = {
        "orderId":null,
        "orderSn":null,
        "batchId":e.batchId,
        "userId":null,
        "memberUsername":null,
        "totalAmount":null,
        "purchasePrice":null,
        "status":null,
        "autoConfirmDay":null,
        "deleteStatus":null,
        "receiveTime":null,
        "deptId":null,
        "deptName":null,
        "pmsBatch":{"batchId":null,"name":null,"number":null,"timeLimitStart":null,"timeLimitEnd":null}
      }
      previewOrder(t).then(resq=>{
        this.tabList = resq.data;
        
        this.isPreviewShow = true;
      })
    }
  }
};
</script>
<style>
.tab-row{
  display: grid;
}
</style>

